package com.phiture.erp.produce.core.job;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import com.phiture.erp.common.enums.ErpAuditStatus;
import com.phiture.erp.produce.common.enums.ErpProduceInBackFlushProcessResultEnum;
import com.phiture.erp.produce.common.enums.ErpProduceInBackFlushStatusEnum;
import com.phiture.erp.produce.core.pojo.vo.ProduceInEventSaveReqVO;
import com.phiture.erp.produce.core.service.ErpProduceInEventService;
import com.phiture.erp.produce.core.service.ErpProduceInService;
import com.phiture.erp.produce.dal.entity.ErpProduceInItemsDO;
import com.phiture.erp.produce.dal.entity.ErpProduceInEventDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 生产入库后审批时进行物料倒冲处理
 *
 * @author lekaihuai
 */
@Slf4j
@Component
public class ProduceInBackFlushJob implements JobHandler {

    @Resource
    private ErpProduceInEventService produceInEventService;

    @Resource
    private ErpProduceInService produceInService;

    @Override
    @TenantJob
    public String execute(String param) {

        List<ErpProduceInEventDO> eventDOList = produceInEventService.getProduceInEventList();
        int successCount = 0;

        for (ErpProduceInEventDO eventDO : eventDOList) {
            try {
                // 获取生产入库单明细
                List<ErpProduceInItemsDO> itemList = produceInService.getProduceInItemsListByProduceInId(eventDO.getProduceInId());
                produceInService.doBackFlushWhenProduceIn(eventDO.getId(), itemList, eventDO.getInType() == ErpAuditStatus.APPROVE.getStatus() ? true : false);
                successCount++;
            } catch (Exception e) {
                // 处理异常，记录日志等
                log.error("执行生产入库后审批时进行物料倒冲处理失败，生产入库事务ID: {}", eventDO.getId(), e);
                // 倒冲出库失败 更新事务处理状态
                ProduceInEventSaveReqVO produceInEventSaveReqVO = new ProduceInEventSaveReqVO();
                produceInEventSaveReqVO.setId(eventDO.getId());
                produceInEventSaveReqVO.setStatus(ErpProduceInBackFlushStatusEnum.ERROR.getStatus());
                produceInEventSaveReqVO.setRemark(e.getMessage());
                produceInEventSaveReqVO.setProcessResult(ErpProduceInBackFlushProcessResultEnum.WAIT_DOING.getStatus());
                produceInEventService.updateProduceInEvent(produceInEventSaveReqVO);
                continue; // 继续处理下一个事务
            }
        }
        return StrUtil.format("执行生产入库后审批时进行物料倒冲处理，待处理的生产入库事务数量为：{};成功处理数量为：{}", eventDOList.size(),successCount);
    }
}
